package news_create_config

import (
	"fmt"
	createConfigDto "news_for_deepseek_interface/dto/admin/news/create_config"
	"news_for_deepseek_interface/model"
	"news_for_deepseek_interface/model/news"
)

func List(params createConfigDto.ListRequest) (response createConfigDto.ListResponse, err error) {
	db := model.GetInstance().GetDB()
	where := map[string]interface{}{}
	if params.Title != nil {
		where["title"] = "%" + *params.Title + "%"
	}

	if params.BasisCreateType != nil {
		where["basis_create_type"] = *params.BasisCreateType
	}

	// 获取总数
	var total int64
	if err = db.Model(&news.NewsCreateConfig{}).Where(where).Count(&total).Error; err != nil {
		err = fmt.Errorf("数量查询失败%s", err.Error())
		return
	}

	// 分页查询
	offset := (params.Page - 1) * params.Limit
	var data []news.NewsCreateConfig
	if err = db.Model(&news.NewsCreateConfig{}).
		Where(where).
		Offset(offset).
		Limit(params.Limit).
		Order("created_at DESC,id desc").
		Find(&data).Error; err != nil {
		err = fmt.Errorf("数据查询失败%s", err.Error())
		return
	}

	// 构建响应
	response = createConfigDto.ListResponse{
		List:  make([]createConfigDto.NewsCreateConfig, 0),
		Total: total,
		Page:  params.Page,
		Limit: params.Limit,
	}

	for _, v := range data {

		response.List = append(response.List, createConfigDto.NewsCreateConfig{
			Id:              v.Id,
			Title:           v.Title,
			BasisCreateType: v.BasisCreateType,
			CreatedAt:       v.CreatedAt.Format("2006-01-02 15:04"),
		})
	}

	return
}
